//
//  WDPersonDetailController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDPersonDetailController.h"
#import "WDPersonMessageView.h"
#import "WDLoginController.h"
#import "WDNavController.h"
#import "WDForgetController.h"
#import "WDLoginController.h"
#import "XFWkwebView.h"
#import "WDCheckUpdataController.h"
#import "ControllerTool.h"
#import "WDPersonMessage.h"

@interface WDPersonDetailController () <WDPersonMessageDelegete,UITableViewDelegate,UITableViewDataSource>
/** 个人信息视图 */
@property (nonatomic, strong) WDPersonMessageView *personMessageView;
/**选项*/
@property (nonatomic, strong)UITableView *optionView;
/**选项数组*/
@property(nonatomic,strong)NSMutableArray *optionArr;
/** 个人数据 */
@property (nonatomic, strong) WDPersonMessage *personMessage;

@end

@implementation WDPersonDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载导航条
    [self loadNavItemWithAction:@selector(clickLeftBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"个人中心"];
    
    //加载视图
    [self setUpPersonMessageView];
    
    [self setUpExitBtn];
    //加载选项视图
    self.optionView = [[UITableView alloc] init];
    [self.view addSubview:self.optionView];
    self.optionView.delegate = self;
    self.optionView.dataSource = self;
    self.optionView.scrollEnabled = NO;
    
    [self.optionView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.personMessageView.bottom).offset(12.5);
        make.left.right.equalTo(0);
        NSInteger height = 48 * self.optionArr.count;
        make.height.equalTo(height);
    }];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self preferredStatusBarStyle];
    
    self.navigationController.navigationBar.hidden = NO;
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)setUpPersonMessageView
{
    self.personMessageView = [[WDPersonMessageView alloc] init];
    
    self.personMessageView.personMessage = self.personMessage;
    
    self.personMessageView.delegete = self;
    
    [self.view addSubview:self.personMessageView];
    
    [self.personMessageView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(15);
        make.left.right.equalTo(0);
        make.height.equalTo(self.personMessageView.personMessage.viewH);
    }];
}

- (void)setUpExitBtn
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.4 alpha:0.4]] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.4 alpha:0.8]] forState:UIControlStateHighlighted];
    
    [btn setTitle:@"退出登录" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(clickExitBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(0);
        make.height.equalTo(48);
    }];
}

#pragma mark - 点击事件
- (void)clickExitBtn
{
    [self showAlertWithTitle:@"提醒" Message:@"你确定要退出当前账号？" leftStr:@"是" rightStr:@"否" leftBtnClick:^{
        
        //发网络请求
        [self requestLoginOut];
        
    } rightClick:^{
        
    }];
}

- (void)clickLeftBtn
{

//    UIViewController *comeVC = [[NSClassFromString(self.comeVC) alloc] init];
//
//    WDNavController *nav = [[WDNavController alloc] initWithRootViewController:comeVC];
    
//    [self.mm_drawerController setCenterViewController:nav];
//    //关闭抽屉控制器
//    [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 退出登录
- (void)requestLoginOut
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"type":@0
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogOut];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //保存用户名
        NSString *tempAccount = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        //保存cid
        NSString *tempCID = [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
        
        //清空数据
        NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
        
        [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
        
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        [manager clearTable:@"WDBusiness"];
        [manager clearTable:@"WDProduct"];
        
        //清除BadgeNumber
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        
        [GeTuiSdk setBadge:0];
        
        WDLoginController *tempV = [[WDLoginController alloc] init];
        
        [[NSUserDefaults standardUserDefaults] setObject:tempAccount forKey:@"userName"];
        
        [[NSUserDefaults standardUserDefaults] setObject:tempCID forKey:@"clientId"];
        
        //清除所有页面
        
        [ControllerTool destroyInstance];
        
        tempV.view.backgroundColor = WDBackColor;
        
        WDNavController *tempNav = [[WDNavController alloc] initWithRootViewController:tempV];
        
        [[UIApplication sharedApplication].delegate window].rootViewController = tempNav;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@",error);
        
    }];
}

#pragma mark - <WDPersonMessageDelegete>
- (void)personMessageShowAlert:(UIAlertController *)alert
{
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)personMessageOpenImagePicker:(UIImagePickerController *)picker
{
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - lazy load
-(NSMutableArray *)optionArr
{
    if (!_optionArr)
    {
        _optionArr = [NSMutableArray arrayWithObjects:@"修改密码", @"版本新功能", @"关于",nil];
    }
    return _optionArr;
}

- (WDPersonMessage *)personMessage
{
    if (!_personMessage) {
        
        _personMessage = [[WDPersonMessage alloc] init];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        _personMessage.iconImage = [userDefault objectForKey:@"userIcon"];
        _personMessage.name = [userDefault objectForKey:@"personName"];
        _personMessage.position = [userDefault objectForKey:@"positioDesc"];
        _personMessage.phoneNumber = [userDefault objectForKey:@"personPhone"];
        _personMessage.mailAddress = [userDefault objectForKey:@"userName"];
        
    }
    return _personMessage;
}

#pragma mark - tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.optionArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.textLabel.text = self.optionArr[indexPath.row];
    cell.textLabel.textColor = ColorForRGB(0x6b6b6b);
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0://跳转修改密码页
        {
            WDForgetController *tempV = [[WDForgetController alloc] init];
            
            tempV.view.backgroundColor = WDBackColor;
            
            [self.navigationController pushViewController:tempV animated:YES];
        }
            
            break;
            
        case 1://版本新功能
        {
            XFWkwebView *webView = [[XFWkwebView alloc] init];
            [webView loadWebURLSring:@"http://zhihjf.com/explain_ios.html"];
            
            [self.navigationController pushViewController:webView animated:YES];
        }
            
            break;
            
        case 2://跳转检查更新页
        {
            WDCheckUpdataController *tempV = [[WDCheckUpdataController alloc] init];
            
            tempV.view.backgroundColor = WDBackColor;
            
            [self.navigationController pushViewController:tempV animated:YES];
        }
            
            break;
            
        default:
            break;
    }
}

@end
